package com.instasale.dao;

import com.instasale.models.Car;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class HibernateCarDAO implements CarDAO {

    private HibernateTemplate hibernateTemplate;

    private static final String HQL_LIST_CARS = "from " + Car.class.getName();

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.hibernateTemplate = new HibernateTemplate(sessionFactory);
    }

    @Override
    public void addCar(Car car) {
        hibernateTemplate.saveOrUpdate(car);
    }

    @Override
    public void removeCar(Integer id) {
        Car car = hibernateTemplate.load(Car.class, id);
        if (car != null) {
            hibernateTemplate.delete(car);
        }
    }

    @Override
    public Car getById(Integer id) {
        return hibernateTemplate.get(Car.class, id);
    }

    @Override
    public List<Car> listCar() {
        return hibernateTemplate.find(HQL_LIST_CARS);
    }

    @Override
    public List<Car> listCar(String orderByColumnName) {
        return hibernateTemplate.find(HQL_LIST_CARS + " order by " + orderByColumnName);
    }

}